<script setup>
  import patientInfo from './components/patientInfo.vue'
  import notifyInfo from './components/notifyInfo.vue'
  import messageInfo from './components/messageInfo.vue'
  import persistionContent from './components/persistionContent.vue'
  import reatInfo from './components/reatInfo.vue'
  import statusInfo from './components/statusInfo.vue'

  import dayjs from 'dayjs'
  import { io } from 'socket.io-client'
  import { http } from '@/utils/http.js'
  import { useloginStore } from '@/store/user.js'
  import { getCurrentInstance, nextTick, onMounted, ref, onUpdated } from 'vue'
  import { patientInfoStore } from '@/store/patient'
  import { getOrderInfoApi } from '@/server/room'
  import { func, image } from '../../uni_modules/uview-plus/libs/function/test'
  // 创建websocket连接
  // 获取网页地址参数
  const props = defineProps(['orderId', 'payResult', 'type'])

  const ishowTab = ref(false)

  // 付款失败返回首页，成功清除数据
  function getisShowfunction() {
    if (props.payResult === 'true') {
      // 清空store中的数据
      const patientStore = patientInfoStore()
      patientStore.illnessInfo = { ...patientStore.illnessValue }
      patientStore.illnessDescInfo.depId = ''
      patientStore.illnessDescInfo.illnessType = ''
      patientStore.illnessDescInfo.type = ''
      patientStore.patidentId = ''

      ishowTab.value = true
    }
  }

  getisShowfunction()

  const socket = io(http.config.baseURL, {
    auth: {
      token: `Bearer ${useloginStore().token}`,
    },
    query: {
      orderId: props.orderId,
    },
    transports: ['websocket', 'polling'],
  })

  // 连接成功
  socket.on('connect', () => {
    console.log('连接成功')
  })

  // 断开连接
  socket.on('disconnect', () => {
    console.log('断开连接')
  })

  // 连接错误
  socket.on('error', (e) => {
    console.log(e)
    console.log('连接错误')
  })

  // 事件端聊天信息分组
  const chatMsgList = ref([])

  // 接收历史信息
  socket.on('chatMsgList', ({ code, data }) => {
    refresherTriggered.value = false
    if (code !== 10000) return uni.utils.toast('接收历史消息错误，请稍后重试！')
    // chatMsgList.value.unshift(data)
    const tempList = []

    // data.forEach(({ createTime, items }, index) =>{

    data.forEach(({ createTime, items }, index) => {
      // 获取消息的时间节点
      if (index === 0) lastTime.value = createTime
      // 追加到消息列表中
      tempList.push(
        {
          msgType: 31,
          msg: { content: createTime },
          id: createTime,
        },
        ...items
      )
    })

    // 是否获取到新数据
    if (tempList.length === 0) return uni.utils.toast('没有更多聊天记录了')
    // 追加到消息列表中
    messageMsgList.value.unshift(...tempList)
    getOrderInfo()
  })

  // 文字图片消息集合
  const ccd = ref('messagebottm')
  const messageMsgList = ref([])

  // 文字图片消息
  socket.on('receiveChatMsg', (res) => {
    messageMsgList.value.push(res)
    getOrderInfo()
  })

  // 获取会诊室状态
  const status = ref(0)
  // 会诊室值
  const statusValue = ref(0)
  // 会诊室倒计时
  const countdown = ref(0)

  socket.on('statusChage', (res) => {
    console.log(res)
    getOrderInfo()
  })

  // 医生详细信息
  const docInfoObj = ref({})
  // 患者详细信息
  const patientInfoList = ref({})

  // 获取订单详情信息
  async function getOrderInfo() {
    const { data } = await getOrderInfoApi(props.orderId)
    // console.log(data)
    if (data.data?.docInfo) {
      docInfoObj.value = data.data?.docInfo
    } else {
      docInfoObj.value.id = 0
    }

    patientInfoList.value = data.data.patientInfo
    status.value = data.data.status
    statusValue.value = data.data.statusValue
    countdown.value = data.data.countdown
  }
  getOrderInfo()

  const userId = useloginStore().userId
  // 发送消息
  const messageStr = ref('')
  function onSendMessagefn(ev) {
    socket.emit('sendChatMsg', {
      from: userId,
      to: docInfoObj?.value?.id,
      msgType: 1,
      msg: {
        content: ev,
      },
    })
    messageStr.value = ''
  }
  // 发送图片
  function onImageSend() {
    uniCloud.chooseAndUploadFile({
      type: 'image',
      count: 1,
      extension: ['.jpg', '.png', '.gif'],
      success(res) {
        const picture = {
          url: res.tempFiles[0].url,
          id: res.tempFiles[0].lastModified,
        }
        socket.emit('sendChatMsg', {
          from: userId,
          to: docInfoObj?.value?.id,
          msgType: 1,
          msg: {
            picture,
          },
        })
      },
    })
  }

  // 自定义下拉刷新
  const refresherTriggered = ref(false)

  const lastTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))

  function onPullDownRefresh() {
    refresherTriggered.value = true
    socket.emit('getChatMsgList', 20, lastTime.value, props.orderId)
  }
</script>
​
<template v-if="ishowTab">
  <view class="room-page">
    <status-info
      :status="status"
      :statusValue="statusValue"
      :countdown="countdown"
    ></status-info>
    <scroll-view
      @refresherrefresh="onPullDownRefresh"
      :refresher-triggered="refresherTriggered"
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <!-- 通知消息和处方消息(历史消息) -->
        <template v-for="(chatMsg, index) in chatMsgList" :key="index">
          <!-- 历史消息时间 -->
          <notify-info>{{ chatMsg.createTime }}</notify-info>
          <!-- 每一项的历史消息 -->
          <template
            v-for="(chatitem, chatitemIndex) in chatMsg.items"
            :key="chatitem.id"
          >
            <!--  患者信息 -->
            <patient-info
              v-if="chatitem.msgType === 21"
              :chatList="chatitem"
            ></patient-info>

            <!-- 通知消息 -->
            <notify-info
              :notifyType="chatitem.msgType"
              v-if="chatitem.msgType >= 31"
              >{{ chatitem.msg.content }}</notify-info
            >
            <!-- 历史会话消息 -->
            <message-info
              v-if="chatitem.msgType === 1 || chatitem.msgType === 4"
              :messageInfo="chatitem"
              :isDocMessage="chatitem.from === docInfoObj.id"
            ></message-info>

            <!-- 处方消息 -->
            <persistion-content
              v-if="chatitem.msgType === 22"
              :persistionInfo="chatitem"
            ></persistion-content>

            <!-- 医生评价 -->
            <reat-info
              v-if="chatitem.msgType === 23 || chatitem.msgType === 24"
              :rate="chatitem"
              :docId="docInfoObj.id"
              :orderId="props.orderId"
            ></reat-info>
          </template>
        </template>

        <!-- 及时会话消息 -->
        <template v-for="item in messageMsgList" :key="item.id">
          <!--  患者信息 -->
          <patient-info
            v-if="item.msgType === 21"
            :chatList="item"
          ></patient-info>

          <!-- 历史消息时间 -->
          <notify-info v-if="item.msgType === 31">{{
            item.msg.content
          }}</notify-info>

          <!-- 通知消息 -->
          <notify-info :notifyType="item.msgType" v-if="item.msgType >= 31">{{
            item.msg.content
          }}</notify-info>

          <!-- 历史会话消息 -->
          <message-info
            v-if="item.msgType === 1 || item.msgType === 4"
            :messageInfo="item"
            :isDocMessage="item.from === docInfoObj.id"
          ></message-info>

          <!-- 文字、图片消息 -->
          <!--     <message-info
            v-if="item.msgType === 1 || item.msgType === 4"
            :messageInfo="item"
            :isDocMessage="item.from === docInfoObj.id"
          ></message-info> -->

          <!-- 处方消息 -->
          <persistion-content
            v-if="item.msgType === 22"
            :persistionInfo="item"
          ></persistion-content>

          <!-- 医生评价 -->
          <reat-info
            v-if="item.msgType === 23 || item.msgType === 24"
            :rate="item"
            :docId="docInfoObj.id"
            :orderId="props.orderId"
          ></reat-info>
        </template>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="status === 3">
        <uni-easyinput
          :disabled="!(status === 3)"
          :clearable="false"
          :input-border="false"
          v-model="messageStr"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
          @confirm="onSendMessagefn"
        />
        <view @click="onImageSend" class="image-button">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import url(./index.scss);
</style>
